package com.juc.learn.semaphore;


import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:CountDownLatchDemo
 * Package:com.juc.learn.countdownlacth
 * Description:信号等
 *
 * @Author:@郭先森
 * @Create:2025/7/27 - 21:03
 * @Version:v1.0
 */
//6辆汽车停在3个停车位
public class SemaphoreDemo {
    public static void main(String[] args) {
        //创建Semaphore对象，设置许可数量
        Semaphore semaphore = new Semaphore(3);

        //模拟6辆汽车
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
               //抢占车位
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了车位");
                    //设置随机停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));

                    System.out.println(Thread.currentThread().getName()+"*********离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //释放
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }

    }
}
